package cn.com.bluemoon.order.print.handler;

import java.io.IOException;

import org.w3c.dom.Element;
import org.xhtmlrenderer.css.parser.property.PrimitivePropertyBuilders.Src;
import org.xhtmlrenderer.extend.FSImage;
import org.xhtmlrenderer.extend.ReplacedElement;
import org.xhtmlrenderer.extend.ReplacedElementFactory;
import org.xhtmlrenderer.extend.UserAgentCallback;
import org.xhtmlrenderer.layout.LayoutContext;
import org.xhtmlrenderer.pdf.ITextFSImage;
import org.xhtmlrenderer.pdf.ITextImageElement;
import org.xhtmlrenderer.render.BlockBox;
import org.xhtmlrenderer.simple.extend.FormSubmissionListener;

import com.lowagie.text.BadElementException;
import com.lowagie.text.Image;

import cn.com.bluemoon.order.print.BarcodeHandler;

public class B64ImgReplacedElementFactory implements ReplacedElementFactory {

	public ReplacedElement createReplacedElement(LayoutContext c, BlockBox box, UserAgentCallback uac, int cssWidth,
			int cssHeight) {
		Element e = box.getElement();
		if (e == null) {
			return null;
		}
		String nodeName = e.getNodeName();
		if (nodeName.equals("img")) {
			String attribute = e.getAttribute("src");
			FSImage fsImage;
			try {
				fsImage = buildImage(attribute, uac);

			} catch (BadElementException e1) {
				e1.printStackTrace();
				fsImage = null;
			} catch (IOException e1) {
				e1.printStackTrace();
				fsImage = null;
			}
			if (fsImage != null) {
				if (cssWidth != -1 || cssHeight != -1) {
					fsImage.scale(cssWidth, cssHeight);
				}
				return new ITextImageElement(fsImage);
			}
			
		}
		return e;

	}

	protected FSImage buildImage(String srcAttr, UserAgentCallback uac) throws IOException, BadElementException {
		FSImage fsImage;
		if (srcAttr.startsWith("data:image/")) {
			String barCode = srcAttr.substring(srcAttr.indexOf("base64,") + "base64,".length(), srcAttr.length());
			
			byte[] decodedBytes = CacheHandler.get(barCode);
			//BarcodeHandler.toImage(decodedBytes);
			// System.out.println(b64encoded);
			// BarcodeHandler.base64StringToImage(b64encoded);
			fsImage = new ITextFSImage(Image.getInstance(decodedBytes));
		} else {
			fsImage = uac.getImageResource(srcAttr).getImage();
		}
		return fsImage;
	}

	public void remove(Element e) {
	}

	public void reset() {
	}

	@Override
	public void setFormSubmissionListener(FormSubmissionListener listener) {
	}
}